package com.quik.web.front.action;

import java.nio.charset.Charset;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.quik.common.Constants;
import com.quik.dto.PaginationDto;
import com.quik.entity.BizBilling;
import com.quik.entity.BizBillingItem;
import com.quik.entity.BizBillingRelatedItem;
import com.quik.entity.DtaProduct;
import com.quik.entity.Room;
import com.quik.entity.SysAccount;
import com.quik.exception.ErrorCode;
import com.quik.web.front.service.ConsultBillingService;
import com.quik.web.front.service.ConsultRoomService;
import com.quik.web.front.service.ConsultTokenService;
import com.quik.web.product.service.ProductService;


/**
 * 功能说明：
 *     咨客-房间业务控制
 * @author jenny
 *
 */
@Controller
@RequestMapping("/consultRoom")
public class ConsultantRoomController {
	private static Logger log = (Logger)Logger.getLogger(ConsultantRoomController.class);
	
	@Autowired
	private ConsultRoomService consultRoomService;
	
	@Autowired
	private ConsultTokenService consultTokenService;
	
	@Autowired
	private ConsultBillingService consultBillingService;
	
	@Autowired
	private ProductService productService;
	
	/**
	 * 查询房间列表
	 * @return
	 */
	@RequestMapping(value = "roomList", method = RequestMethod.GET)
	public ModelAndView roomList(){
		ModelAndView mav = new ModelAndView("/front/consult/room/roomList");
		
		try{
			//获取房间类型
			List roomTypeList = consultRoomService.findRoomTypeList();
			//获取房间区域
			List roomAreaList = consultRoomService.findRoomAreaList();
			//获取房间状态
			List roomStatusList = consultRoomService.findRoomStatusList();
			//获取房间列表
			List roomList = consultRoomService.findRoomList(null, null, null);
			//获取房间统计
			List roomStatList = consultRoomService.findRoomStatList();
			
			mav.addObject("roomTypeList", roomTypeList);
			mav.addObject("roomAreaList", roomAreaList);
			mav.addObject("roomStatusList", roomStatusList);
			mav.addObject("roomList", roomList);
			mav.addObject("roomStatList", roomStatList);
		}catch(Exception e){
			e.printStackTrace();
			log.error("ConsultantRoomController roomList error: " + e.getMessage());
		}
		
		return mav;
	}
	
	/**
	 * 查询房间列表
	 * @param roomType
	 * @param roomArea
	 * @param status
	 * @return
	 */
	@RequestMapping(value = "queryRoomList", method = RequestMethod.POST)
	@ResponseBody
	public List queryRoomList(Integer roomType, Integer roomArea, String status){
		List roomList = null;
		
		try{
			roomList = consultRoomService.findRoomList(roomType, roomArea, 
					status != null && status.trim().length() > 0?status:null);
		}catch(Exception e){
			e.printStackTrace();
			log.error("ConsultantRoomController queryRoomList error: " + e.getMessage());
		}
		
		return roomList;
	}
	
	/**
	 * 房间详情
	 * @param roomId
	 * @param status
	 * @return
	 */
	@RequestMapping(value = "roomDetail", method = RequestMethod.POST)
	public ModelAndView roomDetail(Integer roomId, String status){
		ModelAndView mav = new ModelAndView("/front/consult/room/openRoom");
		
		try{
			Room room = consultRoomService.findRoomById(roomId);
			
			if(status.equals(Room.ROOM_STATUS_FREE)){
				DtaProduct product = consultRoomService.findProductByRoomId(roomId);
				
				//查询商品的大类
				List categoryList = productService.findCategory();				
				
				mav.addObject("product", product);
				mav.addObject("categoryList", categoryList);
			}else{
				mav.setViewName("/front/consult/room/roomDetail");
				
				//查询关联帐单
				List billingList = consultBillingService.findRelateBillingByItemNo(room.getRoom_no().trim(), BizBillingRelatedItem.ITEM_TYPE_ROOM);
				//查询关联房间
				List roomList = consultBillingService.findRelateRoomByBillingId(billingList);
				//查询关联手牌
				List tokenList = consultBillingService.findRelateTokenByBillingId(billingList);
				//查询棋牌消费明细
				List chessList = consultBillingService.findChessConsumeByBillingId(billingList);
				//查询服务消费明细
				List serviceList = consultBillingService.findServiceConsumeByBillingId(billingList);
				//查询其它明细
				List otherList = consultBillingService.findOtherConsumeByBillingId(billingList); 
				
				mav.addObject("tokenList", tokenList);
				mav.addObject("roomList", roomList);
				mav.addObject("billingList", billingList);
				mav.addObject("chessList", chessList);
				mav.addObject("serviceList", serviceList);
				mav.addObject("otherList", otherList);
				mav.addObject("IS_ABLE", BizBillingItem.STATUS_YES);
				mav.addObject("IF_MASTER", BizBilling.MASTER_YES);
				mav.addObject("PRODUCT_YES", DtaProduct.OPTION_FOR_YES);
				mav.addObject("PRODUCT_NO", DtaProduct.OPTION_FOR_NO);
			}
			
			mav.addObject("room", room);
		}catch(Exception e){
			e.printStackTrace();
			log.error("ConsultantRoomController roomDetail error: " + e.getMessage());
		}
		
		return mav;
	}
	
	/**
	 * 手牌开房间
	 *     （通过手牌查到对应的帐单ID，以便生成relate关系）
	 * @param tokenNo
	 * @param roomId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "openRoom", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> openRoom(String tokenNo, String roomNo, String productNo, Integer qty, String service, String chess, HttpServletRequest request){
		SysAccount account = (SysAccount)request.getSession().getAttribute(Constants.SESSION_ACCOUNT);		
		String result = ErrorCode.CONSULT_OPENROOM_FAILED;
		
		//解决返回中文乱码问题
		HttpHeaders headers = new HttpHeaders(); 
		MediaType mediaType=new MediaType("text","html",Charset.forName("UTF-8"));     
		headers.setContentType(mediaType);  
		
		try{
			boolean isToken = consultTokenService.isUsed(tokenNo);
			if(isToken){
				consultRoomService.openRoom(tokenNo, roomNo, productNo, service, chess, qty, account.getStaff_no());
				result = "success";
			}else
				result = ErrorCode.CONSULT_OPENROOM_NO_TOKEN;
		}catch(Exception e){
			e.printStackTrace();
			log.error("ConsultantRoomController openRoom error: " + e.getMessage());
		}
		
		return new ResponseEntity<String>(result, headers, HttpStatus.OK);
	}
	
	/**
	 * 无手牌开房
	 * @param roomNo
	 * @param productNo
	 * @param isService
	 * @param isChess
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "openRoomNoToken", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> openRoomNoToken(String contactStaffNo, String roomNo, String productNo, Integer qty, 
				String service, String chess, HttpServletRequest request){
		String result = ErrorCode.CONSULT_OPENROOM_FAILED;
		SysAccount account = (SysAccount)request.getSession().getAttribute(Constants.SESSION_ACCOUNT);
        
		//解决返回中文乱码问题
		HttpHeaders headers = new HttpHeaders(); 
		MediaType mediaType=new MediaType("text","html",Charset.forName("UTF-8"));     
		headers.setContentType(mediaType);  
		
        try{
        	consultRoomService.openRoomNoToken(contactStaffNo, roomNo, productNo, service, chess, qty, account.getStaff_no());
			result = "success";
        }catch(Exception e){
        	e.printStackTrace();
        	log.error("ConsultantRoomController openRoomNoToken error: " + e.getMessage());
        }
        
        return new ResponseEntity<String>(result, headers, HttpStatus.OK);
	}
	
	/**
	 * 进入交换房间
	 * @return
	 */
	@RequestMapping(value = "initExchangeRoom", method = RequestMethod.GET)
	public String initExchangeToken(){
		return "/front/consult/room/exchangeRoom";
	}
	
	/**
	 * 交换房间
	 * @param srcRoom
	 * @param newRoom
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "exchangeRoom", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> exchangeRoom(String srcRoom, String newRoom, HttpServletRequest request){
		String result = ErrorCode.SYSTEM_ERROR;
		SysAccount account = (SysAccount)request.getSession().getAttribute(Constants.SESSION_ACCOUNT);
		
		//解决返回中文乱码问题
		HttpHeaders headers = new HttpHeaders(); 
		MediaType mediaType=new MediaType("text","html",Charset.forName("UTF-8"));     
		headers.setContentType(mediaType);
		
		try{
			if(consultRoomService.isExchanged(srcRoom, newRoom)){
				consultRoomService.exchangeRoom(srcRoom, newRoom, account.getStaff_no());
				result = "success";
			}else
				result = ErrorCode.CONSULT_EXCHANGE_ROOM_INVALIDROOM;
		}catch(Exception e){
			e.printStackTrace();
			log.error("ConsultantRoomController exchangeRoom error: " + e.getMessage());
		}
		
		return new ResponseEntity<String>(result, headers, HttpStatus.OK);
	}
	
	/**
	 * 初始化关联房间
	 * @return
	 */
	@RequestMapping(value = "initRelateRoom", method = RequestMethod.GET)
	public ModelAndView initRelateRoom(){
		ModelAndView mav = new ModelAndView("/front/consult/room/relateRoom");
		
		try{
			List roomTypeList = consultRoomService.findRoomTypeList();
			List roomAreaList = consultRoomService.findRoomAreaList();
			
			mav.addObject("roomTypeList", roomTypeList);
			mav.addObject("roomAreaList", roomAreaList);
			mav.addObject("roomStatusFree", Room.ROOM_STATUS_FREE);
		}catch(Exception e){
			e.printStackTrace();
			log.error("ConsultantRoomController initRelateRoom error: " + e.getMessage());
		}
		
		return mav;
	}
	
	/**
	 * 根据条件查询空闲状态的房间列表
	 * @param page
	 * @param rows
	 * @param tokenNo
	 * @param tokenType
	 * @return
	 */
	@RequestMapping(value = "queryRoom", method = RequestMethod.POST)
	@ResponseBody
	public PaginationDto queryRoom(Integer page, Integer rows, String roomNo, String status, Integer roomType, Integer roomArea){
		PaginationDto dto = new PaginationDto(0, null);
		
		try{
			int intPage = (page == null || page == 0) ? 1:page;  //当前页
		    int pageSize = (rows == null || rows == 0) ? Constants.TREE_PAGE_SIZE : rows;  //每页显示的记录
		    
		    int totalCount = consultRoomService.findRoomCount(roomNo, roomType, roomArea, status);
		    List list = consultRoomService.findRoomList(roomNo, roomType, roomArea, status, intPage, pageSize);
		    
		    dto.setRows(list);
		    dto.setTotal(totalCount);
		}catch(Exception e){
			e.printStackTrace();
			log.error("ConsultantRoomContorller queryRoom error: " + e.getMessage());
		}
		
		return dto;
	}
	
	/**
	 * 关联房间
	 * @param boundToken
	 * @param relateToken
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "relateByRoom", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> relateByRoom(String boundRoom, String[] relateRoom, HttpServletRequest request){
		SysAccount account = (SysAccount)request.getSession().getAttribute(Constants.SESSION_ACCOUNT);
		String result = ErrorCode.SYSTEM_ERROR;
		
		HttpHeaders headers = new HttpHeaders(); 
		MediaType mediaType=new MediaType("text","html",Charset.forName("UTF-8"));     
		headers.setContentType(mediaType); 
		
		try{
			boolean isRoom = consultRoomService.isRoom(boundRoom.trim());
			if(isRoom){
				consultRoomService.relateByRoom(boundRoom, relateRoom, account.getStaff_no());
				result = "success";
			}else
				result = ErrorCode.CONSULT_EXCHANGE_ROOM_INVALIDROOM;
		}catch(Exception e){
			e.printStackTrace();
			log.error("ConsultantRoomController relateByRoom error: " + e.getMessage());
			
		}
		
		return new ResponseEntity<String>(result, headers, HttpStatus.OK);
	}
	
	/**
	 * 初始化预订房间
	 * @return
	 */
	@RequestMapping(value = "initBookingRoom", method = RequestMethod.GET)
	public ModelAndView initBookingRoom(){
		ModelAndView mav = new ModelAndView("/front/consult/room/bookingRoom");
		
		try{
			List roomTypeList = consultRoomService.findRoomTypeList();
			List roomAreaList = consultRoomService.findRoomAreaList();
			
			mav.addObject("roomTypeList", roomTypeList);
			mav.addObject("roomAreaList", roomAreaList);
			mav.addObject("roomStatusFree", Room.ROOM_STATUS_FREE);
		}catch(Exception e){
			e.printStackTrace();
			log.error("ConsultantRoomController initBookingRoom error: " + e.getMessage());
		}
		
		return mav;
	}
	
	/**
	 * 预订房间
	 * @param roomId
	 * @param userName
	 * @param userMobile
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "bookingRoom", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> bookingRoom(Integer roomId, String userName, String userMobile, String bookingDate, HttpServletRequest request){
		SysAccount account = (SysAccount)request.getSession().getAttribute(Constants.SESSION_ACCOUNT);
		String result = ErrorCode.SYSTEM_ERROR;
		
		HttpHeaders headers = new HttpHeaders(); 
		MediaType mediaType=new MediaType("text","html",Charset.forName("UTF-8"));     
		headers.setContentType(mediaType); 
		
		try{
			boolean isBooking = consultRoomService.isBook(roomId, bookingDate);
			if(isBooking){
				consultRoomService.bookingRoom(roomId, userName, userMobile, bookingDate, account.getStaff_no());
				result = "success";
			}else
				result = ErrorCode.CONSULT_BOOKING_ROOM_INVALID;
		}catch(Exception e){
			e.printStackTrace();
			log.error("ConsultantRoomController bookingRoom error: " + e.getMessage());
		}
		
		return new ResponseEntity<String>(result, headers, HttpStatus.OK);
	}
}
